/*jslint vars: true, forin:true, sloppy: true*/
/*global angular, probe, FileReader*/
probe.controller("dictionaryImportCSV", function ($scope, $element, $filter, ocDialog) {
	$scope.status = '没有文件';
	$scope.separator = '';

	var DI = ocDialog.queryDI($element);
	var dict = DI.share;
	$scope.content = null;

	var fileInput = $element[0].querySelector("#file");
	var dropzone = $element[0].querySelector("#dropzone");

	function fileHandler (file) {
		//should limit file size
		$scope.status = '文件大小' + Math.round(file.size / 1024) + 'kb';

		//use file reader to read file
		var reader = new FileReader();
		//callback hell - not so good
		reader.onload = function (readerEvent) {
			$scope.content = readerEvent.target.result;
			$scope.status = '文件读取完毕';
		};

		reader.onerror = function (readerEvent) {
			$scope.status = '文件读取失败';
			ocDialog.alert({
				title: '文件读取失败',
				message: '文件读取失败，错误代码：' + readerEvent.target.error.code
			});
		};

		reader.readAsText(file);
	}

	function importHandler () {
		var parseResult;
		try {
			//return two dimensional array
			parseResult = $filter("csv")($scope.content, $scope.separator);

			dict.data.field.length = 0;
			dict.head.length = 0;
			angular.forEach(parseResult[0], function (item) {
				dict.data.field.push({
					name: item,
					pattern: 'no data',
					comment: '从csv中导入'
				});
				//reset header
				dict.head.push({
					text: item,
					width: 120
				});
			});
			dict.data.assignment = parseResult.slice(1);
		} catch (e) {
			$scope.status = "导入时出现错误" + e;
			return;
		}

		$scope.status = '导入成功';
		$scope.content = null;
		dict.refresh();
	}

	$scope.parse = function () {
		ocDialog.alert({
			title: '导入',
			message: '您未保存的字典会被覆盖',
			callFn:importHandler
		}, DI);
	};

	dropzone.addEventListener("dragover", function (e) {
		e.preventDefault();
	});

	dropzone.addEventListener("drop", function (e) {
		e.preventDefault();

		var file = e.dataTransfer.files[0];// no multiple import...

		return fileHandler(file);
	});

	fileInput.addEventListener("change", function () {
		var file = fileInput.files[0];// no multiple upload

		return fileHandler(file);
	});
});